//
//  MessageViewController.m
//  DaDaBao
//
//  Created by admin on 15/8/20.
//  Copyright (c) 2015年 User. All rights reserved.
//

#import "MessageViewController.h"
#import "YZSegment.h"
#import "MessageCell.h"
#import "MsgDetailViewController.h"
#import "MessageModel.h"

@interface MessageViewController ()<UITableViewDataSource,UITableViewDelegate,YZSegmentDelegate,UIAlertViewDelegate>
@property(nonatomic,strong)UITableView *messageTable;
@property(nonatomic,strong)YZSegment *segment;
@property(nonatomic,strong)NSMutableArray          *dataArr;
@property(nonatomic,strong)NSMutableArray          *unreadArr;
@property(nonatomic,strong)NSMutableArray          *readArr;
@property (nonatomic, assign) int idx;
@property(nonatomic,strong) UIButton *noDataBt;
@property(nonatomic,strong)UIButton *tipBt;
@property(nonatomic,assign) int n;
@end

@implementation MessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor hexStringToColor:@"#ebebeb"];
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    if (!_unreadArr) {
        _unreadArr = [NSMutableArray array];
    }
    if (!_readArr) {
        _readArr = [NSMutableArray array];
    }
    _idx=0;
    
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:TRUE];
    [self createUI];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloginView) name:@"reLogin" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
}

//UI布局
-(void)createUI
{
    TopView *topView =[[TopView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    [topView setTitile:@"站内通知"];
    UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0.0f, 20.0f, 64.0f, 44.0f)];
    [backBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(buttonBackTapped:) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:backBtn];
    
    [self.view addSubview:topView];
    
    if (!_messageTable) {
        _messageTable = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 64.0f, SCREEN_WIDTH, SCREEN_HEIGHT - 64.0f) style:UITableViewStylePlain];
        _messageTable.delegate = self;
        _messageTable.dataSource = self;
        [_messageTable registerClass:[MessageCell class] forCellReuseIdentifier:@"messageCell"];
        _messageTable.rowHeight = 120.0f;
        _messageTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        __weak __typeof(self) weakSelf = self;
        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
        _messageTable.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf refreshTheMessageTableView];
        }];
        
        // 马上进入刷新状态
        [_messageTable.header beginRefreshing];
        _messageTable.delegate=self;
        _messageTable.dataSource=self;
        _messageTable.sectionHeaderHeight = 40.0f;
        [self.view addSubview:_messageTable];
    }
    if (_messageTable) {
        __weak __typeof(self) weakSelf = self;

        _messageTable.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf refreshTheMessageTableView];
        }];
        
        // 马上进入刷新状态
        [_messageTable.header beginRefreshing];
        
        [_messageTable addSubview:self.tipBt];
        [_messageTable addSubview:self.noDataBt];

    }
    if (!_segment) {
        NSArray *itemTitleArray = @[@"全部",@"未读",@"已读"];
        _segment = [[YZSegment alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 40.0f) btnInformation:itemTitleArray contentOffSet:0];
        _segment.myDelegate = self;
        
    }
}

-(UIButton *)tipBt
{
    if (!_tipBt) {
        _tipBt = [[UIButton alloc]initWithFrame:CGRectMake((SCREEN_WIDTH - 116.0f) / 2.0f, (SCREEN_HEIGHT - 180.0f) / 2.0f, 116.0f, 130.0f)];
        [_tipBt setBackgroundImage:[UIImage imageNamed:@"network_error"] forState:UIControlStateNormal];
        [_tipBt addTarget:self action:@selector(buttonAgainTapped:) forControlEvents:UIControlEventTouchUpInside];
        _tipBt.hidden = TRUE;
    }
    return _tipBt;
}

- (UIButton *)noDataBt
{
    if (!_noDataBt) {
        _noDataBt = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - 116.0f) / 2.0f, (SCREEN_HEIGHT - 180.0f) / 2.0f, 116.0f, 130.0f)];
        [_noDataBt addTarget:self action:@selector(buttonAgainTapped:) forControlEvents:UIControlEventTouchUpInside];
        [_noDataBt setImage:[UIImage imageNamed:@"img_nodata"] forState:UIControlStateNormal];
        _noDataBt.hidden = TRUE;
    }
    return _noDataBt;
}

- (void)buttonAgainTapped:(id)sender
{
    [_messageTable.header beginRefreshing];
}

#pragma mark- tableViewDatasource &delegate

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MessageCell * cell=[[MessageCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"messageCell"];
    UILabel *sepLab = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 120.0f, SCREEN_WIDTH, 0.5f)];
    sepLab.backgroundColor = [UIColor lightGrayColor];
    [cell addSubview:sepLab];
    if (_segment.selectIndex == 0) {
        MessageModel *model = [_dataArr objectAtIndex:indexPath.row];
        cell.titleLab.text = model.title;
        cell.timeLab.text = model.createTime;
        cell.textLab.text = model.messageContent;
    }
    if (_segment.selectIndex == 1) {
        MessageModel *model = [_unreadArr objectAtIndex:indexPath.row];
        cell.titleLab.text = model.title;
        cell.timeLab.text = model.createTime;
        cell.textLab.text = model.messageContent;
    }
    
    if (_segment.selectIndex == 2) {
        MessageModel *model = [_readArr objectAtIndex:indexPath.row];
        cell.titleLab.text = model.title;
        cell.timeLab.text = model.createTime;
        cell.textLab.text = model.messageContent;
    }
    
    
    return cell;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_segment.selectIndex==0)
    {
        return _dataArr.count;
        
    }
    if (_segment.selectIndex==1)
    {
        return _unreadArr.count;
    }
    else
    {
        return _readArr.count;
    }
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return _segment;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    MessageModel *model;
    if (_segment.selectIndex==0) {
        model = [_dataArr objectAtIndex:indexPath.row];
        if ([model.status intValue] == 0) {
            [_unreadArr removeObject:model];
            [_readArr addObject:model];
            [tableView reloadData];
        }
    }
    if (_segment.selectIndex==1) {
        model = [_unreadArr objectAtIndex:indexPath.row];
        [_unreadArr removeObject:model];
        [_readArr addObject:model];
        if (_unreadArr.count==0) {
            _noDataBt.hidden = TRUE;
        }
        [tableView reloadData];
    }
    if (_segment.selectIndex==2) {
        model = [_readArr objectAtIndex:indexPath.row];
    }
    if ([model.status intValue]== 0)
    {
        [self updateUserMessageStatus:model];
    }
    MsgDetailViewController *msgVC = [[MsgDetailViewController alloc] init];
    msgVC.msgTitle = model.title;
    msgVC.msgTime = model.createTime;
    msgVC.msgText = model.messageContent;
    
    [self.navigationController pushViewController:msgVC animated:TRUE];
    
}

-(void)reloginView
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"登录失败，请重新登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}

-(void)updateUserMessageStatus:(MessageModel *)model
{
    [AppGlobalClass PostDataWithNSstring:UPDATE_USER_MESSAGE_URL withDictionary:@{@"token":[[NSUserDefaults standardUserDefaults] objectForKey:@"token"],@"userMessageId":model.userMessageId,@"status":@1} success:^(NSDictionary *dictionary) {
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]]) {
        }
    } failure:^(NSError *error) {
        
    } networkerror:^(NSString *networkerror) {
        
    }];
}

#pragma mark alertDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [AppGlobalClass exitLogin];
    LoginViewController *loginViewCon = [[LoginViewController alloc]init];
    [self presentViewController:loginViewCon animated:TRUE completion:^{}];
    
    NSArray *listArray = self.navigationController.viewControllers;
    
    id tabBar = [listArray objectAtIndex:1];
    if([[tabBar class] isSubclassOfClass:[UITabBarController class]])
    {
        UITabBarController *tabBarCon = tabBar;
        tabBarCon.selectedIndex = 0;
        [self.navigationController popToViewController:[listArray objectAtIndex:1] animated:TRUE];
    }
    else
    {
        UITabBarController *tabBarCon = [listArray objectAtIndex:2];
        tabBarCon.selectedIndex = 0;
        [self.navigationController popToViewController:[listArray objectAtIndex:2] animated:TRUE];
    }
}

#pragma mark-刷新表
-(void)refreshTheMessageTableView
{
    _idx=0;
    _n = 0;
    [self getHttpData];
}
#pragma mark-加载更多数据
- (void)AddtoTheMessageTableView
{
    [self getHttpData];
 }
- (void)getHttpData
{
    
    [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];
    
    _tipBt.hidden = TRUE;
    _noDataBt.hidden = TRUE;
    
    NSDictionary *dict = @{ @"page.size":[NSNumber numberWithInt:10],@"page.pn":[NSNumber numberWithInt:_idx + 1], @"token":[[NSUserDefaults standardUserDefaults] objectForKey:@"token"]};
    [AppGlobalClass PostDataWithNSstring:GET_USER_MESSAGE_URL withDictionary:dict success:^(NSDictionary *dictionary){
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
            [_messageTable.header endRefreshing];
            [_messageTable.footer setState:MJRefreshStateIdle];
            [_messageTable.footer endRefreshing];

            if(_idx == 0)
            {
                [_dataArr removeAllObjects];
                [_unreadArr removeAllObjects];
                [_readArr removeAllObjects];
            }
            NSArray *dataArray = [dictionary objectForKey:@"responseData"];
            NSDictionary *dataDict = [dataArray objectAtIndex:0];
            
            if([[dataDict objectForKey:@"pages"] intValue] > _idx)
            {
                NSMutableArray *listArray = [[[dictionary objectForKey:@"responseData"]firstObject] objectForKey:@"rows"];
                
                for(int i = 0; i < listArray.count; i++)
                {
                    MessageModel *model = [[MessageModel alloc]initWithDictionary:[listArray objectAtIndex:i]];
                    [_dataArr addObject:model];
                    if ([model.status intValue]== 0)
                    {
                        [_unreadArr addObject:model];
                    }
                    if ([model.status intValue] == 1) {
                        [_readArr addObject:model];
                    }
                    
                }
                
                _idx++;
     
                if(listArray.count < 10)
                {
                    [_messageTable.footer noticeNoMoreData];
                    
                }
                else
                {
                    if (_segment.selectIndex==0) {
                        _n++;
                        if (_n<2) {
                              _messageTable.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(AddtoTheMessageTableView)];
                        }
                    }
                }
                if (_segment.selectIndex==1) {
                    if (_unreadArr.count<10)
                    {
                        [_messageTable.footer noticeNoMoreData];
                        if (_unreadArr.count==0)
                        {
                            _noDataBt.hidden = FALSE;
                        }
                        
                    }
                    else
                    {
                        _n++;
                        if (_n<2) {
                            _messageTable.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(AddtoTheMessageTableView)];
                        }

                        
                    }
                    
                }
                if (_segment.selectIndex==2) {
                    if (_readArr.count<10)
                    {
                        [_messageTable.footer noticeNoMoreData];
                        if (_readArr.count==0)
                        {
                           _noDataBt.hidden = FALSE;
                        }
                        
                    }
                    else
                    {
                        _n++;
                        if (_n<2) {
                            _messageTable.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(AddtoTheMessageTableView)];
                        }
                    }
                }
                
                [_messageTable reloadData];
                
            }
            else
            {
                if (self.dataArr.count==0) {
                    _noDataBt.hidden = FALSE;
                    
                }
                
                [self.messageTable.footer noticeNoMoreData];
                
            }
        }
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
        
    } failure:^(NSError *error){
        
        [self.readArr removeAllObjects];
        [self.dataArr removeAllObjects];
        [self.unreadArr removeAllObjects];
        [self.messageTable reloadData];
        
        [_messageTable.header endRefreshing];
        [_messageTable.footer setState:MJRefreshStateIdle];
        [_messageTable.footer endRefreshing];
        
        _noDataBt.hidden = FALSE;

        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
    } networkerror:^(NSString *networkerror){
    
        [self.readArr removeAllObjects];
        [self.dataArr removeAllObjects];
        [self.unreadArr removeAllObjects];
        [self.messageTable reloadData];
        
        [_messageTable.header endRefreshing];
        [_messageTable.footer setState:MJRefreshStateIdle];
        [_messageTable.footer endRefreshing];
        
        _tipBt.hidden = FALSE;
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
    }];
}
#pragma mark - YZSegmentDelegate
- (void)view:(UIScrollView *)view didSelectIndex:(NSInteger)indexOfButton
{
    __weak __typeof(self) weakSelf = self;
    switch (indexOfButton)
    {
        case 0:
        {
            [weakSelf refreshTheMessageTableView];
            
        }
            break;
        case 1:
        {
            [weakSelf refreshTheMessageTableView];
        }
            break;
        case 2:
        {
            [weakSelf refreshTheMessageTableView];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark-返回方法
-(void)buttonBackTapped:(id)sender
{
    [self.navigationController popViewControllerAnimated:TRUE];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
